package com.my9yu.common.socket.filter.transience;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


/**
 * 属性类，用于统一与简化对{@link TransientSession}的属性操作<br/>
 * 所有属性都将放在以{@link Session#MAIN_KEY}作为KEY，对应的{@link ConcurrentHashMap}中
 * @author Ramon
 */
@SuppressWarnings("unchecked")
public class TransientAttribute<T> {

	/** 属性键 */
	private final String key;

	/**
	 * 构建属性对象
	 * @param key 属性键
	 */
	public TransientAttribute(String key) {
		this.key = key;
	}

	/**
	 * 获取会话中的全部属性
	 * @param session
	 * @return
	 */
	public ConcurrentMap<String, Object> getAttributes(TransientSession session) {
		ConcurrentMap<String, Object> attributes = session.getContent();
		return attributes;
	}

	/**
	 * 获取属性值
	 * @param session
	 * @return
	 */
	public T getValue(TransientSession session) {
		ConcurrentMap<String, Object> attributes = session.getContent();
		return (T) attributes.get(key);
	}

	/**
	 * 获取属性值，不存在则以默认值返回
	 * @param session
	 * @param defaultValue 默认值
	 * @return
	 */
	public T getValue(TransientSession session, T defaultValue) {
		if (contain(session)) {
			return getValue(session);
		}
		return defaultValue;
	}

	/**
	 * 设置属性值
	 * @param session
	 * @param value
	 * @return
	 */
	public T setValue(TransientSession session, T value) {
		ConcurrentMap<String, Object> attributes = session.getContent();
		return (T) attributes.put(key, value);
	}

	/**
	 * 检查是否存在对应的属性值
	 * @param session
	 * @return
	 */
	public boolean contain(TransientSession session) {
		ConcurrentMap<String, Object> attributes = session.getContent();
		return attributes.containsKey(key);
	}

	/**
	 * 获取属性键
	 * @return
	 */
	public String getKey() {
		return key;
	}

	@Override
	public String toString() {
		return key;
	}
}
